package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.service.IDbBackupAndRecoverService;
import cn.wolfcode.crm.util.JsonResult;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("database")
public class DatabaseController {
    @Autowired
    private IDbBackupAndRecoverService dbBackupAndRecoverService;
    @Autowired
    private ServletContext ctx;

    @RequestMapping("backup")
    public void backup(HttpServletResponse response) throws Exception {
        String filename = dbBackupAndRecoverService.backup();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        String dir = ctx.getRealPath("/static/database");
        Files.copy(Paths.get(dir, filename), response.getOutputStream());
        File file = new File(dir);
        if (file.exists()) {
            String[] files = file.list();
            for (String s : files) {
                File file1 = new File(dir + "/" + s);
                file1.delete();
            }
        }
    }

    @RequestMapping("recover")
    @ResponseBody
    public JsonResult recover(MultipartFile file) {
        String dir = ctx.getRealPath("/static/database");
        JsonResult jsonResult = new JsonResult();
        try {
            if (file != null) {
                String filename = file.getOriginalFilename();
                File oldFile = new File(dir + "/" + filename);
                if (oldFile != null) {
                    oldFile.delete();
                }
                Files.copy(file.getInputStream(), Paths.get(dir, filename));
                String filepath = dir + "/" + filename;
                dbBackupAndRecoverService.recover(filepath);
            } else {
                throw new RuntimeException("无文件备份,请选择文件");
            }
            return jsonResult;
        } catch (Exception e) {
            e.printStackTrace();
            return jsonResult.mark("还原失败,原因:" + e.getMessage());
        }
    }
}
